from rest_framework.exceptions import ValidationError
from rest_framework import serializers
from django_redis import get_redis_connection
from api.pagination.validator import phone_validator, email_validator
from utils import encrypt


class MessageSerializer(serializers.Serializer):
    phone = serializers.CharField(label="手机号", validators=[phone_validator])


class LoginSerializer(serializers.Serializer):
    phone = serializers.CharField(label="手机号", validators=[phone_validator, ])
    code = serializers.CharField(label="验证码", error_messages={'blank': "验证码不能为空"})

    def validate_code(self, attrs):
        if len(attrs) != 4:
            raise ValidationError('短信格式错误')
        if not attrs.isdecimal():
            raise ValidationError('短信格式错误')
        phone = self.initial_data.get('phone')
        conn = get_redis_connection()
        code = conn.get(phone)

        if not code:
            raise ValidationError('验证码已过期,请获取重新获取')
        if attrs != code.decode('utf-8'):
            raise ValidationError('验证码错误')
        return attrs


class UsernamephoneSerializer(serializers.Serializer):
    phone = serializers.CharField(label="手机号", validators=[phone_validator, ])
    password = serializers.CharField(label="用户密码", min_length=7, max_length=15)

    def validate_password(self, attr):
        # 加密 & 返回
        return encrypt.md5(attr)


class UsernameEmailSerializer(serializers.Serializer):
    email = serializers.CharField(label="邮箱", validators=[email_validator, ])
    password = serializers.CharField(label="用户密码", min_length=7, max_length=15)

    def validate_password(self, attr):
        # 加密 & 返回
        return encrypt.md5(attr)


class ResetPasswordSerializer(serializers.Serializer):
    password = serializers.CharField(label="用户密码")
    pwd1 = serializers.CharField(label="新密码第一次")
    pwd2 = serializers.CharField(label="新密码验证")

    def validate_password(self, attr):
        password = encrypt.md5(attr)
        if self.context['request'].user.password != password:
            raise ValidationError("密码错误")
        # 加密 & 返回
        return password

    def validate_pwd1(self, value):
        pwd2 = self.context['request'].data.get('pwd2')
        if value != pwd2:
            raise ValidationError("两次密码不一致")
        return encrypt.md5(value)


class SetPasswordSerializer(serializers.Serializer):
    pwd1 = serializers.CharField(label="新密码第一次")
    pwd2 = serializers.CharField(label="新密码验证")

    def validate_pwd1(self, value):
        pwd2 = self.context['request'].data.get('pwd2')
        if value != pwd2:
            raise ValidationError("两次密码不一致")
        return encrypt.md5(value)
